import {
  API_DOMAIN,
  API_STATIC
} from '../utils/api.config'
const Promise = require('../libs/bluebird') // 为了兼容问题

/**
 * 请求API接口
 * @param  {String}      api 根地址
 * @param  {String} path   请求路径
 * @param  {Objece} params 参数
 * @return {Promise}       包含抓取任务的Promise
 */
module.exports = function (api, path, params, method) {
  if (!params) {
    params = {};
  }

  // if (params && !params.channelName) {
  //   params.channelName = 'applet';
  // }

  return new Promise((resolve, reject) => {
    var tokenId = wx.getStorageSync('tokenId');

    var header = {
      'Content-Type': 'application/json',
    }
    if (tokenId && tokenId.length > 1) {
      header.Authorization = tokenId;
    }
    var tempApi = api
    var newDateTime = '';
    if (params.static) {
      tempApi = API_STATIC;
      newDateTime = '?' + Date.parse(new Date())
    } else if (path.indexOf('https://') != -1) {
      tempApi = '';
    }

    var method1 = method || "post"
    wx.request({
      url: `${tempApi}${path}${newDateTime}`,
      data: Object.assign({}, params), // 如果这里需要合并签名时间戳参数时候可以这么写
      header: header,
      method: method1,
      success: (res) => {

        if (res.data && res.success == false && res.data.retCode == "0005") {


          wx.setStorageSync('userData', '');

          wx.setStorageSync('tokenId', '');

          wx.hideLoading()

          setTimeout(function () {
            let pages = getCurrentPages();
            if (pages && pages.length > 0) {
              var i = pages[pages.length - 1].route;

              if (i && i == 'pages/index/index') {
                // 同一个页面不让跳

              } else {
                wx.redirectTo({
                  url: '/pages/index/index?isRoot=true'
                });
              }
            } else {
              wx.redirectTo({
                url: '/pages/index/index?isRoot=true'
              });
            }
          }, 500)


        } else {
          resolve(res)
        }

      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}